package com.example.exam.controller;

import com.example.exam.entity.DTO.LoginDTO;
import com.example.exam.entity.User;
import com.example.exam.service.UserServiceImpl;
import com.example.exam.utils.JsonUtils;
import com.example.exam.utils.JwtUtils;
import com.example.exam.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhang
 */
@RestController
@RequestMapping("/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private JsonUtils<User> jsonUtils;
    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/login")
    public String login(@RequestBody LoginDTO loginUser) {
        //TODO:登录逻辑
        User user = new User();
        BeanUtils.copyProperties(loginUser, user);
        String token = jwtUtils.createToken(user);
        redisUtils.set(token, jsonUtils.t2String(user), 2);
        return token;
    }

    @DeleteMapping("/{token}")
    public String logout(@PathVariable String token) {
        redisUtils.delete(token);
        return "logout";
    }


    @PostMapping("/{token}")
    public ResponseEntity<String> activation(@PathVariable String token, @RequestBody User newUser) {
        User oldUser = (User) redisUtils.get(token, User.class);
        boolean status = userService.activationUser(oldUser, newUser);
        return ResponseEntity.ok("activation");
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException(Exception ex) {
        // 在这里处理异常
        return "Exception caught in MyController: " + ex.getMessage();
    }
}
